import mongoose, { Document, Schema } from 'mongoose';
import { IMaintenanceRecord, MaintenanceType } from '@/types';

export interface IMaintenanceDocument
  extends Omit<IMaintenanceRecord, '_id'>,
    Document {}

const maintenanceSchema = new Schema<IMaintenanceDocument>(
  {
    userId: {
      type: String,
      required: [true, '用户ID是必需的'],
    },
    vehicleId: {
      type: String,
      required: [true, '车辆ID是必需的'],
    },
    date: {
      type: Date,
      required: [true, '保养日期是必需的'],
      default: Date.now,
    },
    odometer: {
      type: Number,
      required: [true, '里程表是必需的'],
      min: [0, '里程表不能为负数'],
    },
    type: {
      type: String,
      enum: Object.values(MaintenanceType),
      required: [true, '保养类型是必需的'],
    },
    laborCost: {
      type: Number,
      required: [true, '工时费是必需的'],
      min: [0, '工时费不能为负数'],
    },
    partsCost: {
      type: Number,
      required: [true, '配件费是必需的'],
      min: [0, '配件费不能为负数'],
    },
    totalCost: {
      type: Number,
      required: [true, '总费用是必需的'],
      min: [0, '总费用不能为负数'],
    },
    description: {
      type: String,
      trim: true,
      maxlength: [500, '描述不能超过500个字符'],
    },
    nextMaintenanceOdometer: {
      type: Number,
      min: [0, '下次保养里程不能为负数'],
    },
    nextMaintenanceDate: {
      type: Date,
    },
  },
  {
    timestamps: true,
  }
);

// 索引
maintenanceSchema.index({ userId: 1 });
maintenanceSchema.index({ vehicleId: 1 });
maintenanceSchema.index({ type: 1 });
maintenanceSchema.index({ date: 1 });
maintenanceSchema.index({ userId: 1, vehicleId: 1 });
maintenanceSchema.index({ userId: 1, date: 1 });

export const Maintenance = mongoose.model<IMaintenanceDocument>(
  'Maintenance',
  maintenanceSchema
);
